import concurrent.futures
import os
import time
from pathlib import Path
from PIL import Image


image_dir = Path(r"E:\手机备份\DCIM\Camera")
image_extensions = {".png", ".jpg", ".jpeg", ".bmp", ".gif"}

total_files_checked = 0
files_with_errors = 0
start_time = time.time()

default_thread_count = os.cpu_count()
print(f"默认线程池大小: {default_thread_count}")


def check_image(image_path):
    global total_files_checked, files_with_errors
    total_files_checked += 1
    try:
        print(f"【{total_files_checked}】,{image_path.name}")
        with Image.open(image_path) as img:
            img.load()
    except (FileNotFoundError, OSError, IOError) as e:
        print(f"文件 {image_path} 可能已损坏: {e}")
        files_with_errors += 1


with concurrent.futures.ThreadPoolExecutor() as executor:
    future_to_image_path = {
        executor.submit(check_image, image_path): image_path
        for image_path in image_dir.glob("**/*.*")
        if image_path.suffix in image_extensions
    }

end_time = time.time()
execution_time = end_time - start_time

print("总计检查:", total_files_checked)
print("可能损坏:", files_with_errors)
print("执行时间:", execution_time, "秒")
